#include "DataReceiver.h"
#include "CIpodLog.h"

// 构造函数：接受超时时间和 std::function 回调函数
DataReceiver::DataReceiver(int timeout_ms, std::function<void()> timeout_callback)
    : timeout_ms(timeout_ms), timeout_callback(timeout_callback), data_received(false), stop(false) {
    // 启动超时检测线程
    timeout_thread = std::thread(&DataReceiver::checkTimeout, this);
}

DataReceiver::~DataReceiver() {
    stop = true;
    if (timeout_thread.joinable()) {
        timeout_thread.join();
    }
}

void DataReceiver::receiveData() {
    std::lock_guard<std::mutex> lock(mutex_);
    last_received_time = std::chrono::steady_clock::now();
    data_received = true;
//    std::cout << "收到新数据，重新计时..." << std::endl;
    CIpodLog::i("[ DataReceiver ] DataReceiver::receiveData 收到新数据，重新计时... \n");
}

void DataReceiver::checkTimeout() {
    while (!stop) {
        std::this_thread::sleep_for(std::chrono::milliseconds(2));  // 每50ms检查一次

        std::lock_guard<std::mutex> lock(mutex_);
        if (data_received) {
            // 计算当前时间与最后一次收到数据的时间差
            auto now = std::chrono::steady_clock::now();
            auto duration_since_last_received = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_received_time);

            if (duration_since_last_received.count() > timeout_ms) {
//                std::cout << "超过" << timeout_ms << "ms未收到数据，触发超时处理！" << std::endl;
                CIpodLog::i("[ DataReceiver ] DataReceiver::checkTimeout 超过   timeout_ms %d  ms未收到数据，触发超时处理！ \n",timeout_ms);
                data_received = false;  // 停止超时计时，等待下一次数据接收
                if (timeout_callback) {
                    timeout_callback();  // 调用回调函数
                }
            }
        }
    }
}
